<template>
  <div class="region-list">
    <div>{{ checkNodes }}</div>
    <div
      v-for="(area,index) in regions"
      :key="index"
      class="region"
    >
      <div class="region-head">
        <el-checkbox
          v-model="area.checkAll"
          :indeterminate="area.isIndeterminate"
          @change="handleCheckAllChange($event, area)"
        >{{ area.name }}</el-checkbox>
      </div>
      <div class="region-content">
        <checkbox
          v-if="area.children && area.children.length"
          :value="area.children"
          @change="handleCheckedChange($event, index)"
        />
        <el-checkbox-group
          v-else
          v-model="area.checks"
          @change="handleCheckedAreasChange($event, area, index)"
        >
          <div
            v-for="child in area.children"
            :key="child.id"
            class="node-box"
          >
            <el-checkbox :label="child.id">
              {{ child.name }}
            </el-checkbox>
          </div>
        </el-checkbox-group>
      </div>
    </div>
  </div>
</template>

<script>
// import { explainTreeLeaf } from '@/utils'
export default {
  name: 'Checkbox',
  props: {
    titles: {
      type: Array,
      default: () => {
        return ['列表 1', '列表 2']
      }
    },
    value: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data() {
    return {
      checkAll: false,
      checkedAreas: [1],
      cities: ['上海', '北京', '广州', '深圳'],
      isIndeterminate: true
    }
  },
  computed: {
    regions: {
      get() {
        return this.value
      },
      set(v) {
        console.log('set', v)
        this.$emit('change', v)
      }
    },
    checkNodes() {
      return []
    }
  },
  watch: {
    regions: {
      handler(v) {
        console.log('regions change:', v)
        this.$emit('change', v)
      },
      deep: true
    }
  },
  mounted() {},
  methods: {
    handleCheckedChange(val, index) {
      console.log('children changed', index, val)
      this.$set(this.regions, index, val)
    },
    handleCheckAllChange(val, data) {
      if (val) {
        console.log(val)
        data.checks =
          data.children &&
          data.children.map(item => {
            return item.id
          })
      } else {
        data.checks = []
      }
      console.log(data)
      this.isIndeterminate = false
    },
    handleCheckedAreasChange(value, data, index) {
      const checkedCount = value.length
      data.checkAll = checkedCount === data.children.length
      data.isIndeterminate = checkedCount > 0 && checkedCount < data.children.length
      this.$set(this.regions, index, data)
    }
  }
}
</script>
<style lang="scss" scoped>
.region {
  display: flex;
  &-head {
    flex: 1;
  }
  &-content {
    flex: 3;
  }
}
</style>

